package com.chatim.nonamechatim.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chatim.nonamechatim.common.Res;
import com.chatim.nonamechatim.mapper.UserApplyMapper;
import com.chatim.nonamechatim.pojo.User;
import com.chatim.nonamechatim.pojo.UserApply;
import com.chatim.nonamechatim.service.UserFriendService;
import com.chatim.nonamechatim.service.UserService;
import com.chatim.nonamechatim.vo.AddMsgByUserVo;
import com.chatim.nonamechatim.vo.UpdatePasswordVo;
import com.chatim.nonamechatim.vo.UserListVo;
import com.chatim.nonamechatim.vo.UserSearchVo;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    UserApplyMapper userApplyMapper;

    @Resource
    UserFriendService userFriendService;

    /**
     * 注册
     */
    @PostMapping("/register")
    public Res<Boolean> register(@RequestBody User user){
        return Res.success(userService.register(user), "注册成功！");
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/updateUserInfo")
    public Res<Boolean> updateUserInfo(@RequestBody User user){
        return Res.success(userService.updateById(user), "修改成功！");
    }

    // 修改个人头像
    @GetMapping("/updateAvatar")
    public Res<Boolean> updateAvatar(@Param("id")Long id, @Param("header")String header){
        User user = new User();
        user.setId(id);
        user.setAvatar(header);
        return Res.success(userService.updateById(user), "修改成功！");
    }

    /**
     * 修改用户密码
     */
    @PostMapping("/updatePassword")
    public Res<String> updatePassword(@RequestBody UpdatePasswordVo form){
        // 旧密码对比
        String password = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getId, form.getId())).getPassword();
        if(!Objects.equals(password, "{noop}" + form.getPassword())){
            return Res.error("原密码不正确");
        }
        // 更新旧密码
        User user = new User();
        user.setId(form.getId());
        user.setPassword("{noop}" + form.getNewPassword());
        userService.updateById(user);
        return Res.success("更新成功","更新成功");
    }

    /**
     * 根据用户名查找用户信息
     */
    @GetMapping("/infoByUsername")
    public Res<User> getInfo(@Param("username")String username){
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        user.setPassword("******");
        return Res.success(user);
    }

    /**
     * 根据用户id查找用户信息
     */
    @GetMapping("/infoByUid")
    public Res<User> getInfoByUid(@Param("id")Long id){
        User user = userService.getById(id);
        user.setPassword("******");
        return Res.success(user);
    }

    /**
     * 模糊查询用户（非好友）
     */
    @GetMapping("/fuzzyQueryByAddUser")
    public Res<List<UserSearchVo>> fuzzyQueryByAddUser(@Param("uid")Long uid, @Param("key")String key){
        return Res.success(userService.fuzzyQueryByAddUser(uid, key));
    }

    /**
     * 发送添加请求
     */
    @PostMapping("/addApply")
    public Res<String> addApply(@RequestBody UserApply apply){
        int res = userApplyMapper.insert(apply);
        if(res == 1) return Res.success("", "发送成功！");
        else return Res.error("发送失败！");
    }

    /**
     * 查看添加信息
     */
    @GetMapping("/getAddMsg")
    public Res<List<List<AddMsgByUserVo>>> getAddMsg(@Param("id")Long id){
        List<AddMsgByUserVo> msgList = userApplyMapper.getAddMsg(id);
        // 时间降序
        msgList.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
        // 记录顺序id(保证添加消息按时间有序不重复)
        LinkedHashSet<Long> ids = new LinkedHashSet<>();
        msgList.forEach(m -> ids.add(m.getUid()));
        // 根据uid分组
        Map<Long, List<AddMsgByUserVo>> sortByDate = msgList.stream()
                .collect(Collectors.groupingBy(AddMsgByUserVo::getUid));
        // 根据id排序map
        List<List<AddMsgByUserVo>> resList = new ArrayList<>();
        for(Long uid : ids){
            resList.add(sortByDate.get(uid));
        }
        return Res.success(resList);
    }

    // 同意添加好友请求
    @GetMapping("/agreeApply")
    public Res<Boolean> agreeApply(@Param("id")Long id, @Param("fid")Long fid){
        return Res.success(userService.agreeApply(id, fid),"添加成功！");
    }

    // 获取好友列表
    @GetMapping("/getFriendList")
    public Res<List<UserListVo>> getFriends(@Param("id")Long id){
        return Res.success(userFriendService.getFriendList(id));
    }

}
